package com.yz.jdd.module.reg.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.EditTextUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.login.view.LoginActivity;
import com.yz.jdd.module.login.view.LoginView;
import com.yz.jdd.module.main.MainActivity;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_UserLogin;
import com.yz.jdd.network.request.Request_UserRegister;
import com.yz.jdd.network.response.Response_UserLogin;
import com.yz.jdd.webview.H5BridgeActivity;
import com.yz.jdd.webview.download.H5DownFileUtils;

import java.util.Arrays;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 注册
 */
public class RegistActivity extends BaseActivity {

    @BindView(R.id.top_back)
    TextView topBack;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.btn_register)
    Button btn_register;
    @BindView(R.id.tv_get_code)
    TextView tv_get_code;//获取验证码
    @BindView(R.id.edit_phone)
    EditText edit_phone;//手机号码
    @BindView(R.id.edit_password)
    EditText edit_password;//密码
    @BindView(R.id.edit_verification_code)
    EditText edit_verification_code;//验证码
    @BindView(R.id.edit_invitation_code)
    EditText edit_invitation_code;//邀请码
    @BindView(R.id.user_xieyi)
    TextView userXieyi;


    private static LoginView loginView;
    private String verification_code = "";//验证码
    private int timeLength = 60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);
        topTitle.setText("注册");
        topBack.setText("返回");
        btn_register.setEnabled(false);

        EditTextUtils.inputTextCheck(btn_register, Arrays.<TextView>asList(edit_phone,edit_password,edit_verification_code));
    }

    public static void invoke(Activity activity, String phone) {
        Intent intent = new Intent(activity, RegistActivity.class);
        intent.putExtra("register_phone", phone);
        activity.startActivity(intent);
        loginView = (LoginActivity) activity;
    }

    @OnClick({R.id.top_back, R.id.btn_register, R.id.tv_get_code, R.id.user_xieyi})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back://返回
                hideKeyboard();
                loginView = null;
                finish();
                break;
            case R.id.btn_register://注册
                checkParameter();
                break;
            case R.id.tv_get_code://获取验证码
                String phone = edit_phone.getText().toString();
                if (checkPhoneNumber(phone)) {
                    doSendVerify(phone);
                }
                break;
            case R.id.user_xieyi:
                Intent intent = new Intent(RegistActivity.this, H5BridgeActivity.class);
                String sessionId=PreferencesUtils.getString(this, BaseConfigs.PREF_SESSIONID);
                intent.putExtra("sessionId",sessionId);
                String main_url = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + "vuepages/index.html#/registerLicense?s=" +
                        sessionId+
                        "&statusBarHeight=0&android=4.1" + "&SDK=" + Build.VERSION.SDK_INT
                        + "&url=" + PreferencesUtils.getString(RegistActivity.this, BaseConfigs.STRING_SERVER_URL, Constants.SERVER_URL);
                intent.putExtra(Constants.H5_WEB_URL, main_url);
                startActivity(intent);
                break;
        }
    }


    private MyHandler mHandler = new MyHandler(this);

    private void updateTimeLength() {
        if (timeLength == 0) {
            tv_get_code.setText("重新获取验证码");
            tv_get_code.setEnabled(true);
            tv_get_code.setTextColor(getResources().getColor(R.color.color_FF211A));
            timeLength = 60;
        } else {
            tv_get_code.setEnabled(false);
            tv_get_code.setTextColor(getResources().getColor(R.color.color_a5a5a5));
            tv_get_code.setText(timeLength + "s");
            timeLength--;
            mHandler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    private static class MyHandler extends Handler {

        private RegistActivity registActivity;

        public MyHandler(RegistActivity registActivity) {
            this.registActivity = registActivity;
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                if (registActivity != null) {
                    registActivity.updateTimeLength();
                }
            }
        }
    }

    /**
     * 检查参数并注册
     */
    private void checkParameter() {
        String phone = edit_phone.getText().toString();
        if (!checkPhoneNumber(phone)) {
            return;
        }
        String password = edit_password.getText().toString();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请填写新密码", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if (password.indexOf(" ") != -1 || password.length() < 6 || password.length() > 14) {
                Toast.makeText(this, "新密码长度为6-14位英文、数字组合", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        String verification_code = edit_verification_code.getText().toString();
        if (TextUtils.isEmpty(verification_code)) {
            Toast.makeText(this, "请填写验证码", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if (verification_code.length() < 6) {
                Toast.makeText(this, "请填写正确的验证码", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        String invitation_code = edit_invitation_code.getText().toString();
        if (!TextUtils.isEmpty(invitation_code)) {
            if (invitation_code.length() < 6 || Tools.isContainChinese(invitation_code)) {
                Toast.makeText(this, " 请输入有效的邀请码", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        doRegister(phone, password, verification_code, invitation_code);
    }

    /**
     * 检查手机号码
     *
     * @param phoneNumber 手机号码
     */
    private boolean checkPhoneNumber(String phoneNumber) {
        boolean isPhoneNumber = false;
        if (TextUtils.isEmpty(phoneNumber)) {
            Toast.makeText(this, "请填写手机号", Toast.LENGTH_SHORT).show();
        } else if (phoneNumber.length() < 11) {
            Toast.makeText(this, "请填写有效的手机号", Toast.LENGTH_SHORT).show();
        } else if (!Pattern.matches("^(0|86|17951)?(1[0-9])[0-9]{9}$", phoneNumber)) {
            Toast.makeText(this, "请填写有效的手机号", Toast.LENGTH_SHORT).show();
        } else {
            isPhoneNumber = true;
        }
        return isPhoneNumber;
    }

    /**
     * 获取验证码
     *
     * @param phone
     */
    private void doSendVerify(String phone) {
        showLoading("正在发送验证码...");
        Request_UserLogin request_userLogin = new Request_UserLogin();
        request_userLogin.setMobile(phone);
        NetWorkRequset.doSendVerify(request_userLogin, new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                Toast.makeText(RegistActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                timeLength = 60;
                mHandler.sendEmptyMessage(0);
                PreferencesUtils.putLong(MyApplication.application, "sendVerify_time", System.currentTimeMillis());
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();
            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    Toast.makeText(RegistActivity.this, response_baseModel.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 注册用户
     *
     * @param phone
     * @param password
     * @param verificationCode
     * @param invitationCode
     */
    private void doRegister(String phone, String password, String verificationCode, String invitationCode) {
        showLoadingNoCancelable("加载中...");
        Request_UserRegister request_userRegister = new Request_UserRegister();
        request_userRegister.setAccount(phone);
        request_userRegister.setPassword(password);
        request_userRegister.setVerifyCode(verificationCode);
        request_userRegister.setInvitationCode(invitationCode);
        request_userRegister.setLon(PreferencesUtils.getString(MyApplication.application, BaseConfigs.STRING_LON, "0"));
        request_userRegister.setLat(PreferencesUtils.getString(MyApplication.application, BaseConfigs.STRING_LAT, "0"));
        request_userRegister.setGuid(PreferencesUtils.getString(MyApplication.application, BaseConfigs.STRING_GUID, ""));
        request_userRegister.setNetworkType(AppUtils.getNetWorkType(this));
        NetWorkRequset.doRegister(request_userRegister, new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                Toast.makeText(RegistActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                Response_UserLogin response = (Response_UserLogin) response_baseModel.getResultObject();
                if (response != null) {
                    PreferencesUtils.putString(MyApplication.application, BaseConfigs.PREF_USERNAME, response.getUserName());
                    PreferencesUtils.putString(
                            MyApplication.application,
                            BaseConfigs.PREF_SHOPNAME, response.getShopName());

                    PreferencesUtils.putBoolean(MyApplication.application, BaseConfigs
                            .PREF_VERIFICATION_FLAG, response.isVerificationFlag());

                    PreferencesUtils.putString(MyApplication.application, BaseConfigs
                            .STRING_ROUTERCODE, response.getRouterCode());

                    PreferencesUtils.putString(MyApplication.application, BaseConfigs
                            .POS_SUPPLIERCODE, response.getSupplierCode());

                    String sessionId = response.getSessionId();
                    if (!TextUtils.isEmpty(sessionId)) {
                        PreferencesUtils.putString(MyApplication.application, BaseConfigs.PREF_SESSIONID, sessionId);
                    }
                    String regionName=response.getRegionName();
                    PreferencesUtils.putString(MyApplication.application,
                            BaseConfigs.STRING_REGIONNAME, regionName);


                    String rc = response.getRc();
                    if (!TextUtils.isEmpty(rc)) {
                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.STRING_ROUTE_CODE, rc);
                    }

                    if (response.getMenuInfo() != null) {
                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREF_MENUINFO, new Gson().toJson(response.getMenuInfo()));
                    }


                    startMainActivity();
                    loginView.close();
                    loginView = null;
                    finish();
                }
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();
            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    Toast.makeText(RegistActivity.this, response_baseModel.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        long time = PreferencesUtils.getLong(MyApplication.application, "sendVerify_time", -1);
        long mTime = System.currentTimeMillis() - time;
        if (time != -1 && mTime < 60000 && timeLength == 60) {
            tv_get_code.setEnabled(false);
            tv_get_code.setTextColor(getResources().getColor(R.color.color_a5a5a5));
            timeLength = (int) (60000 - mTime) / 1000;
            mHandler.sendEmptyMessage(0);
        } else {
            if ("获取验证码".equals(tv_get_code.getText().toString().trim())) {
                tv_get_code.setEnabled(true);
                tv_get_code.setTextColor(getResources().getColor(R.color.color_FF211A));
            } else {
                tv_get_code.setEnabled(false);
                tv_get_code.setTextColor(getResources().getColor(R.color.color_a5a5a5));
            }
        }


    }
}
